const Follow = require('../models/Follow')
const {pagination} = require('../utils/utils')
const Article = require('../models/Article')
const User = require('../models/User')
exports.postFollow = async (req, res, next) => {
  const followeeId = req.params.followeeId
  console.log('followeeId: ', followeeId)
  const followerId = req._id
  console.log('followerId: ', followerId)
  try {
    const followExists = await Follow.findOne({
      followerId,
      followeeId,
    })
    console.log('followExists: ', followExists)
    if (followExists) {
      // 如果关注已存在，执行取消关注
      await Follow.deleteOne({_id: followExists._id})
      await User.updateOne({_id: followeeId}, {$inc: {follow_num: -1}})
      res.success({follow: 0}, '取消关注成功')
    } else {
      // 如果关注不存在，执行关注
      const newFollow = new Follow({
        followerId,
        followeeId,
      })
      await newFollow.save()
      await User.updateOne({_id: followeeId}, {$inc: {follow_num: 1}})
      res.success({follow: 1}, '关注成功')
    }
  } catch (error) {
    next(error)
  }
}

exports.getFollowList = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10
  const followerId = req.query.authorId
  const loggedInUserId = req._id || ''
  try {
    // 调用分页方法
    let paginateResult = await pagination({
      model: Follow,
      select: '-createdAt',
      pageNumber,
      pageSize,
      query: {followerId},
      populate: {
        path: 'followeeId', // 需要填充的字段
        select: '-roles -createdAt -updatedAt', // 填充的字段
      },
    })
    if(loggedInUserId){
      // 提取文章作者的所有被关注者的ID列表
      const articleAuthorFolloweeIds = paginateResult.list.map(follow => follow.followeeId._id.toString());
      // 2. 查询登录用户的关注列表,限制在文章作者的所有被关注者的ID列表
      const loggedInUserFollows = await  Follow.find({followeeId: {$in: articleAuthorFolloweeIds}, followerId: loggedInUserId});
      // 提取登录用户关注者的ID列表
      const loggedInUserFolloweeIds = loggedInUserFollows.map(follow => follow.followeeId.toString());
      // 3. 比较两个列表，找出共有的用户ID
      const commonFolloweeIds = articleAuthorFolloweeIds.filter(_id => loggedInUserFolloweeIds.includes(_id));
      // 4. 构建展示列表
      paginateResult = paginateResult.list.map(follow => {
        const isFollowed = commonFolloweeIds.includes(follow.followeeId._id.toString());
        return {
          _id:follow._id,
          followerId:follow.followerId,
          followeeId: follow.followeeId, // 被关注者的用户信息
          followStatus: isFollowed ? 1 : 0, // 添加登陆用户关注状态
        };
      });
    }else{
      paginateResult = paginateResult.list.map(follow => {
        return {
          _id:follow._id,
          followerId:follow.followerId,
          followeeId: follow.followeeId, // 被关注者的用户信息
          followStatus: 0, // 添加登陆用户关注状态
        };
      });
    }
    res.success(paginateResult, '我的关注列表查询成功')
  } catch (err) {
    next(err)
  }
}
